#!/bin/bash

echo "🔧 Electron 安装问题解决方案"
echo ""

# 检查当前目录
if [ ! -f "package.json" ]; then
    echo "❌ 请在项目根目录执行此脚本"
    exit 1
fi

echo "📋 检测到的问题："
echo "   - 网络连接问题 (ECONNRESET)"
echo "   - Electron 二进制文件下载失败"
echo "   - 可能的权限问题"
echo ""

echo "🛠️ 尝试解决方案..."
echo ""

# 方案 1: 清理缓存
echo "1️⃣ 清理 npm 和 Electron 缓存..."
npm cache clean --force 2>/dev/null
rm -rf ~/.electron 2>/dev/null
rm -rf ~/Library/Caches/electron 2>/dev/null

# 方案 2: 设置镜像
echo "2️⃣ 设置国内镜像..."
npm config set registry https://registry.npmmirror.com
export ELECTRON_MIRROR="https://cdn.npmmirror.com/binaries/electron/"
export ELECTRON_BUILDER_BINARIES_MIRROR="https://cdn.npmmirror.com/binaries/electron-builder-binaries/"

# 方案 3: 创建 .npmrc
echo "3️⃣ 创建 .npmrc 配置..."
cat > .npmrc << EOF
registry=https://registry.npmmirror.com
electron_mirror=https://cdn.npmmirror.com/binaries/electron/
electron_builder_binaries_mirror=https://cdn.npmmirror.com/binaries/electron-builder-binaries/
cache=/tmp/.npm
EOF

# 方案 4: 尝试安装特定版本的 Electron
echo "4️⃣ 尝试安装兼容版本的 Electron..."
npm install --save-dev electron@25.9.8 --verbose

if [ $? -eq 0 ]; then
    echo "✅ Electron 安装成功！"
    echo ""
    echo "🚀 现在可以运行："
    echo "   npm run electron:start"
    echo ""
else
    echo "❌ Electron 安装仍然失败"
    echo ""
    echo "🔄 替代方案："
    echo ""
    echo "📱 使用演示版本："
    echo "   python3 -m http.server 8080"
    echo "   然后访问: http://localhost:8080/demo.html"
    echo ""
    echo "💻 使用已构建的应用："
    echo "   cd app-package"
    echo "   修改 start.sh，添加以下内容："
    echo "   echo '跳过 Electron 安装，直接使用系统浏览器'"
    echo "   open index.html"
    echo ""
    echo "🌍 或者升级 Node.js 到 20.19+ 后重试"
fi

echo ""
echo "📝 如果所有方案都失败，建议："
echo "   1. 检查网络连接"
echo "   2. 使用 VPN 或代理"
echo "   3. 升级 Node.js 版本"
echo "   4. 手动下载 Electron 二进制文件"
